package com.sgb.kjwl.view.ui.activity.lease;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityZulinMechanicalBinding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.sgb.kjwl.model.entity.lease.LeaseListEntity;
import com.sgb.kjwl.model.entity.request.CarFilterJson;
import com.sgb.kjwl.model.entity.request.FactoryFilterJson;
import com.sgb.kjwl.model.entity.request.FarmFilterJson;
import com.sgb.kjwl.model.entity.request.HouseFilterJson;
import com.sgb.kjwl.model.entity.request.LandFilterJson;
import com.sgb.kjwl.model.entity.request.LeaseMachineFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.house.LeaseCategoryListActivity;
import com.sgb.kjwl.view.ui.adapter.machine.LeaseListAdapter;
import com.sgb.kjwl.view.ui.adapter.machine.LeaseListTopAdapter;
import com.sgb.kjwl.view.ui.fragment.home.ChildLeaseAskFragment;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.home.ZulinMechanicalModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.FragPagerAdapter;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration2;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class ZulinMechanicalActivity extends AppActivity implements View.OnClickListener {

    @Inject
    ZulinMechanicalModel viewModel;
    private ActivityZulinMechanicalBinding binding;

    private List<DictEntity3> typeDictEntityList = new ArrayList<>();//分类
    private ThreeLevelAreaWindow mAddressPop;
    private LeaseListTopAdapter topAdapter;//顶部的adapt
    private DictWindow5 sortWindow;
    private LeaseListAdapter adapter;
    private List<DictEntity3> sortDictEntityList;//排序的
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> areaEntityList;
    private String provinceName = "";
    private String cityName = "";

    private String type = "1";
    private String title = "";
    private int pageNum = 1;//当前页码
    public int pageSize = 10;//每页条数
    private List<String> cityList = new ArrayList<>();
    private String provinceNo = "";
    private String cityNo = "";
    private String isSelf;//是否自营,1为自营
    private String sortWay = "1";
    private final String[] titles = {"机械租赁", "设备租赁", "车辆租赁", "房产租赁", "土地租赁", "工厂租赁", "农机租赁"};

    public static void start(Context context, String type, String title) {
        Intent intent = new Intent();
        intent.setClass(context, ZulinMechanicalActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);
    }


    @Override
    protected void initView() {
        super.initView();
        initExtra();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_zulin_mechanical);

//        binding.include.titleView.setText(title);
        viewModel.getFilterTypeModel(type);
        binding.ivBack.setOnClickListener(this);
        binding.areaLayout.setOnClickListener(this);
        binding.isSelfLayout.setOnClickListener(this);
        binding.sortLayout.setOnClickListener(this);
        binding.ivMap.setOnClickListener(this);
        provinceNo = viewModel.getAreaCodeModel();
        initRecycler();
        initFilterView();
        initLeaseReleaseView();
    }

    @Override
    protected void init() {
        initTab();
        loadData(false);
    }

    protected void initTab() {
        initExtra();
        ArrayList mFragments = new ArrayList<>();
        for (int i = 0; i < titles.length; i++) {
            mFragments.add(ChildLeaseAskFragment.newInstance(0));//空白实例，临时使用代替方案，后期需优化
        }

        initExtra();
        FragPagerAdapter pagerAdapter = new FragPagerAdapter(getSupportFragmentManager(), mFragments);
        binding.viewpager.setAdapter(pagerAdapter);
        binding.viewpager.setOffscreenPageLimit(titles.length);
        binding.tablayout.setViewPager(binding.viewpager, titles);
        binding.tablayout.setCurrentTab(Integer.parseInt(type) - 1);
        binding.tablayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                type = String.valueOf(position + 1);
                viewModel.getFilterTypeModel(type);
                loadData(false);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    private void loadData(boolean isLoadMore) {
        pageNum = isLoadMore ? pageNum + 1 : 1;
        if ("1".equals(type) || "2".equals(type)) {//接口入参字段不统一,兼容接口不同参数名称
            LeaseMachineFilterJson filterJson = new LeaseMachineFilterJson();
            filterJson.setType(type);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setAreaNoList(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getMachineModel(filterJson, isLoadMore);
        } else if ("3".equals(type)) {
            CarFilterJson filterJson = new CarFilterJson();
            filterJson.setType(type);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setDistrictNo(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getMachineModel(filterJson, isLoadMore);
        } else if ("4".equals(type)) {
            HouseFilterJson filterJson = new HouseFilterJson();
            filterJson.setType(type);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setAreaNoList(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getMachineModel(filterJson, isLoadMore);
        } else if ("5".equals(type)) {
            LandFilterJson filterJson = new LandFilterJson();
            filterJson.setType(type);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setAreaNos(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getMachineModel(filterJson, isLoadMore);
        } else if ("6".equals(type)) {
            FactoryFilterJson filterJson = new FactoryFilterJson();
            filterJson.setType(type);
            filterJson.setIsSelf(isSelf);
            filterJson.setAreacode(provinceNo);
            filterJson.setCity(cityNo);
            filterJson.setArea(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getMachineModel(filterJson, isLoadMore);
        } else if ("7".equals(type)) {
            FarmFilterJson filterJson = new FarmFilterJson();
            filterJson.setType(type);
            filterJson.setIsSelf(isSelf);
            filterJson.setAreacode(provinceNo);
            filterJson.setCity(cityNo);
            filterJson.setArea(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getMachineModel(filterJson, isLoadMore);
        }

    }

    private void initRecycler() {
        topAdapter = new LeaseListTopAdapter(this);
        adapter = new LeaseListAdapter(getActivity(), null);
        adapter.setOnItemClick(new AdapterOnItemClick<LeaseListEntity>() {
            @Override
            public void onItemClick(LeaseListEntity entity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5Url(entity.getType(), entity.getDataId());
                }
            }
        });
        binding.recyclerView.addItemDecoration(new RecyclerViewItemDecoration2(getResources().getDimension(R.dimen.dp10), getResources().getDimension(R.dimen.dp10)));
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        binding.recyclerView.setFootViewText("加载中", "我也是有底线的");
        binding.recyclerView.setAdapter(adapter);

        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.isSelf_layout://是否自营
                if (TextUtils.isEmpty(isSelf)) {
                    isSelf = "1";
                    binding.isSelfLayout.setBackgroundResource(R.drawable.search_new_blue_bg);
                    binding.tvIsSelf.setTextColor(getResources().getColor(R.color.color_main));
                } else {
                    isSelf = "";
                    binding.isSelfLayout.setBackgroundResource(R.drawable.search_bg);
                    binding.tvIsSelf.setTextColor(getResources().getColor(R.color.color_333333));
                }
                loadData(false);
                break;
            case R.id.area_layout:
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopWindowDropDown(binding.selectLayout, getResources().getDimensionPixelOffset(R.dimen.dp1));
                if (areaEntityList == null) {
                    viewModel.getCityData();
                }
                break;
            case R.id.sort_layout://排序
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? -1 : 1, null);
                sortWindow.setCheckDefaultById(sortWay);
                sortWindow.showPopWindowDropDown(binding.sortLayout, getResources().getDimensionPixelOffset(R.dimen.dp1));
                if (sortDictEntityList == null) {
                    viewModel.getFilterSort();
                }
                break;
            case R.id.iv_map://打开地图定位
                startMap();
                break;
        }
    }

    private void initExtra() {
        Intent intent = getIntent();
        if (intent != null) {
            type = intent.getStringExtra("type");
            title = intent.getStringExtra("title");
        }
    }

    public void showTypePopWindow(List<DictEntity3> data) {
        if (data == null) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getName().equals("不限")) {
                data.remove(i);
            }
        }

        int spanCount = 5;
        if (data.size() > 10) {
            spanCount = data.size() / 2;
            if (data.size() % 2 > 0) {
                spanCount += 1;
            }
        }
        binding.rvTop.setLayoutManager(new GridLayoutManager(this, spanCount));
        binding.rvTop.setAdapter(topAdapter);
        topAdapter.setOnItemClick(new AdapterOnItemClick<DictEntity3>() {
            @Override
            public void onItemClick(DictEntity3 bean, int position) {
                LeaseCategoryListActivity.start(ZulinMechanicalActivity.this, type, bean.getId(), bean.getName());
            }
        });
        this.typeDictEntityList.clear();
        this.typeDictEntityList.addAll(data);
        topAdapter.clearDatas();
        topAdapter.addDatas(typeDictEntityList);
    }

    public static int dp2px(Activity activity, int dpValue) {
        float scale = activity.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public void showList(List<LeaseListEntity> list, boolean isLoadMore) {
        binding.recyclerView.setNoMore(list.size() < viewModel.pageSize);
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }

            binding.recyclerView.refreshComplete();
            adapter.setDatas(list);
        }
    }

    public void showSortPopWindow(List<DictEntity3> data) {
        this.sortDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        if (sortWay == null || sortWay.equals("")) {
            sortWay = data.get(0).getId();
        }
        sortWindow.setData(data);
        sortWindow.setCheckDefaultById(sortWay);
    }

    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        this.areaEntityList = data;
        if (data != null && data.size() > 0) {
            this.provinceNo = provinceNo;
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    private void initFilterView() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;

                cityList = getCityList(listKey3);
                if (listKey2 != null && listKey2.size() > 0) {
                    cityName = listKey2.get(0).getName();
                    cityNo = listKey2.get(0).getNo();
                } else {
                    cityNo = "";
                }
                provinceNo = listKey1.get(0).getNo();
                provinceName = listKey1.get(0).getName();
                if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
                    updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, cityName);
                } else {
                    updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, provinceName);
                }
            } catch (Exception exception) {
            }

            loadData(false);
        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
        });


        //排序选择
        sortWindow = new DictWindow5(getActivity());
        sortWindow.setFocusable(true);
        sortWindow.setOutsideTouchable(true);
        sortWindow.setOnCallBack(dictEntity -> {
            updateChooseTextStatus(binding.sortLayout, binding.tvSort, 2, dictEntity.getName());
            sortWay = dictEntity.getId();
            loadData(false);
        });
        sortWindow.setOnCloseBack(() -> updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? 0 : 2, null));
    }

    private void initLeaseReleaseView() {
//        binding.leaseRelease.setOnCallBlackListener(new LeaseReleaseView.OnCallBlackListener() {
//            @Override
//            public void onMap() {
//                Intent intent = new Intent();
//                intent.setClass(getActivity(), SelectAddressActivity.class);
//                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
//                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
//                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
//                intent.putExtra(SelectAddressActivity.LATITUDE, 0);
//                intent.putExtra(SelectAddressActivity.LONGTITUDE, 0);
//                startActivityForResult(intent, 255);
//            }
//        });
    }

    private List<String> getCityList(List<BaseAreaEntity> list) {
        cityList = new ArrayList<>();
        for (BaseAreaEntity entity : list) {
            if (!TextUtils.isEmpty(entity.getNo())) {
                cityList.add(entity.getNo());
            }
        }
        return cityList;
    }

    //更新选项颜色
    private void updateChooseTextStatus(View view, TextView textView, int value, String name) {
        if (value == 0) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
        }
        if (TextUtils.isEmpty(name)) return;
        textView.setText(name);
    }

    //设置背景色和图标
    private void setTextViewBg(View view, TextView textView, int bg, int img, int textColor) {
        view.setBackgroundResource(bg);
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

//    //更新选项颜色
//    private void updateChooseTextStatus(TextView textView, int value, String name) {
//        if (!TextUtils.isEmpty(name)) {
//            textView.setText(name);
//        }
//        if (value == 0) {
//            setTextViewBg(textView, R.mipmap.ic_down_arrow_n, R.color.color_333333);
//        } else if (value == -1) {
//            setTextViewBg(textView, R.mipmap.ic_up_arrow_n, R.color.color_333333);
//        } else if (value == 1) {
//            setTextViewBg(textView, R.mipmap.icon_up_red, R.color.color_main);
//        } else if (value == 2) {
//            setTextViewBg(textView, R.mipmap.icon_down_red, R.color.color_main);
//        }
//    }
//
//    //设置背景色和图标
//    private void setTextViewBg(TextView textView, int img, int textColor) {
//        Drawable drawable_n = getResources().getDrawable(img);
//        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
//        textView.setCompoundDrawables(null, null, drawable_n, null);
//        textView.setTextColor(getResources().getColor(textColor));
//    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == Activity.RESULT_OK) {
//            if (requestCode == 255) {
//                if (data == null) {
//                    return;
//                }
//                double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
//                double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
//                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
//                binding.leaseRelease.setAddressText(address, lat, lon);
//            }
//        }
//    }

    public void startMap() {
        Intent intent = new Intent();
        intent.setClass(this, SelectAddressActivity.class);
        intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
        intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
        intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
        if(!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude",""))){
            intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude","")));
            intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(SharedPreferenceUtil.getInstance().getSaveStringData("distance_longitude","")));
        }
        startActivityForResult(intent, 255);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 255 && data != null) {
                double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
                double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
                //保存定位数据,用来给后端传参计算距离
                SharedPreferenceUtil.getInstance().saveData("distance_latitude", String.valueOf(lat));
                SharedPreferenceUtil.getInstance().saveData("distance_longitude", String.valueOf(lon));
                loadData(false);
            }
        }
    }
}
